<template>
  <view class="expert-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="goToSearch">
        <u-icon name="search" size="18" color="#999"></u-icon>
        <text class="search-placeholder">搜索专家...</text>
      </view>
    </view>
    
    <!-- 分类标签 -->
    <view class="category-tabs">
      <scroll-view class="tabs-scroll" scroll-x>
        <view class="tabs-list">
          <view 
            v-for="(category, index) in categories" 
            :key="index"
            class="tab-item"
            :class="{ active: currentCategory === category.id }"
            @click="switchCategory(category.id)"
          >
            <text class="tab-text">{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 专家列表 -->
    <scroll-view 
      class="expert-list" 
      scroll-y 
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
    >
      <view 
        v-for="(expert, index) in expertList" 
        :key="expert.id"
        class="expert-item"
        @click="viewExpert(expert)"
      >
        <view class="expert-header">
          <view class="expert-avatar-container">
            <u-avatar :src="expert.avatar" size="60"></u-avatar>
            <view class="online-status" :class="{ online: expert.isOnline }"></view>
          </view>
          <view class="expert-info">
            <view class="expert-name-row">
              <text class="expert-name">{{ expert.name }}</text>
              <view v-if="expert.isVerified" class="verified-badge">
                <u-icon name="checkmark" size="12" color="white"></u-icon>
              </view>
            </view>
            <text class="expert-title">{{ expert.title }}</text>
            <text class="expert-hospital">{{ expert.hospital }}</text>
          </view>
          <view class="expert-actions">
            <view class="rating-info">
              <u-icon name="star-fill" size="14" color="#ffd700"></u-icon>
              <text class="rating-text">{{ expert.rating }}</text>
            </view>
            <text class="consult-count">{{ formatCount(expert.consultCount) }}次咨询</text>
          </view>
        </view>
        
        <view class="expert-specialties">
          <text class="specialty-label">擅长：</text>
          <text class="specialty-text">{{ expert.specialties.join('、') }}</text>
        </view>
        
        <view class="expert-stats">
          <view class="stat-item">
            <text class="stat-label">从业</text>
            <text class="stat-value">{{ expert.experience }}年</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">好评率</text>
            <text class="stat-value">{{ expert.goodRatePercent }}%</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">响应时间</text>
            <text class="stat-value">{{ expert.responseTime }}</text>
          </view>
        </view>
        
        <view class="expert-footer">
          <view class="price-info">
            <text class="price-label">图文咨询</text>
            <text class="price-value">¥{{ expert.textPrice }}</text>
          </view>
          <view class="price-info">
            <text class="price-label">语音咨询</text>
            <text class="price-value">¥{{ expert.voicePrice }}</text>
          </view>
          <u-button 
            type="primary" 
            size="small" 
            @click.stop="consultExpert(expert)"
          >
            立即咨询
          </u-button>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">
        <u-loading-icon></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 没有更多 -->
      <view v-if="noMore" class="no-more">
        <text class="no-more-text">没有更多专家了</text>
      </view>
    </scroll-view>
    
    <!-- 专家详情弹窗 -->
    <u-popup 
      v-model="showExpertDetail" 
      mode="bottom" 
      height="70%"
      border-radius="20"
      closeable
    >
      <view class="expert-detail-popup" v-if="selectedExpert">
        <view class="detail-header">
          <view class="expert-avatar-large">
            <image class="avatar-img" :src="selectedExpert.avatar" mode="aspectFill"></image>
            <view class="online-indicator" :class="{ online: selectedExpert.isOnline }">
              <text class="status-text">{{ selectedExpert.isOnline ? '在线' : '离线' }}</text>
            </view>
          </view>
          <view class="expert-basic-info">
            <text class="expert-name-large">{{ selectedExpert.name }}</text>
            <text class="expert-title-large">{{ selectedExpert.title }}</text>
            <view class="expert-level-large" :class="`level-${selectedExpert.level}`">
              <text class="level-text">{{ getLevelText(selectedExpert.level) }}</text>
            </view>
          </view>
        </view>
        
        <view class="detail-content">
          <view class="detail-section">
            <text class="section-title">专业领域</text>
            <view class="specialties-list">
              <text 
                v-for="(specialty, idx) in selectedExpert.specialties" 
                :key="idx"
                class="specialty-tag"
              >
                {{ specialty }}
              </text>
            </view>
          </view>
          
          <view class="detail-section">
            <text class="section-title">专家介绍</text>
            <text class="expert-description">{{ selectedExpert.fullDescription || selectedExpert.description }}</text>
          </view>
          
          <view class="detail-section">
            <text class="section-title">服务统计</text>
            <view class="stats-grid">
              <view class="stat-item">
                <text class="stat-number">{{ formatCount(selectedExpert.consultationCount) }}</text>
                <text class="stat-label">咨询次数</text>
              </view>
              <view class="stat-item">
                <text class="stat-number">{{ selectedExpert.rating }}</text>
                <text class="stat-label">评分</text>
              </view>
              <view class="stat-item">
                <text class="stat-number">{{ selectedExpert.responseTime }}</text>
                <text class="stat-label">响应时间</text>
              </view>
              <view class="stat-item">
                <text class="stat-number">¥{{ selectedExpert.price }}</text>
                <text class="stat-label">咨询费用</text>
              </view>
            </view>
          </view>
          
          <view class="detail-section" v-if="selectedExpert.workTime">
            <text class="section-title">工作时间</text>
            <text class="work-time">{{ selectedExpert.workTime }}</text>
          </view>
        </view>
        
        <view class="detail-actions">
          <button 
            class="action-btn secondary" 
            @click="addToFavorites(selectedExpert)"
          >
            收藏专家
          </button>
          <button 
            class="action-btn primary" 
            @click="startConsultation(selectedExpert)"
          >
            {{ selectedExpert.isOnline ? '立即咨询' : '预约咨询' }}
          </button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';

// 专家接口
interface Expert {
  id: string;
  name: string;
  avatar: string;
  title: string;
  hospital: string;
  description?: string;
  fullDescription?: string;
  specialties: string[];
  experience: number;
  rating: number;
  consultCount: number;
  consultationCount: number;
  goodRatePercent: number;
  responseTime: string;
  textPrice: number;
  voicePrice: number;
  price: number;
  isVerified: boolean;
  isOnline: boolean;
  level: number;
  workTime?: string;
  category: string;
}

// 分类接口
interface Category {
  id: string;
  name: string;
}

@Component
export default class ExpertPage extends Vue {
  // 数据属性
  currentCategory: string = 'all';
  expertList: Expert[] = [];
  
  loading: boolean = false;
  refreshing: boolean = false;
  noMore: boolean = false;
  page: number = 1;
  pageSize: number = 20;
  
  // 专家详情弹窗
  showExpertDetail: boolean = false;
  selectedExpert: Expert | null = null;
  
  categories: Category[] = [
    { id: 'all', name: '全部' },
    { id: 'pediatrics', name: '儿科' },
    { id: 'nutrition', name: '营养' },
    { id: 'psychology', name: '心理' },
    { id: 'education', name: '早教' },
    { id: 'nursing', name: '护理' }
  ];
  
  // 生命周期
  onLoad() {
    this.loadExperts();
  }
  
  onShow() {
    this.refreshExperts();
  }
  
  onPullDownRefresh() {
    this.onRefresh();
  }
  
  onReachBottom() {
    this.loadMore();
  }
  
  // 方法
  
  /**
   * 加载专家
   */
  async loadExperts(isRefresh: boolean = false) {
    if (this.loading) return;
    
    this.loading = true;
    
    try {
      const response = await get('/experts/list', {
        category: this.currentCategory,
        page: isRefresh ? 1 : this.page,
        pageSize: this.pageSize
      });
      
      const newExperts = response.data.experts || [];
      
      if (isRefresh) {
        this.expertList = newExperts;
        this.page = 1;
        this.noMore = false;
      } else {
        this.expertList = [...this.expertList, ...newExperts];
      }
      
      // 检查是否还有更多数据
      if (newExperts.length < this.pageSize) {
        this.noMore = true;
      } else {
        this.page++;
      }
      
    } catch (error) {
      console.error('加载专家失败:', error);
      
      // 使用模拟数据
      if (isRefresh || this.expertList.length === 0) {
        this.expertList = this.getMockExperts();
      }
      
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.loading = false;
      this.refreshing = false;
      uni.stopPullDownRefresh();
    }
  }
  
  /**
   * 刷新专家
   */
  async refreshExperts() {
    this.refreshing = true;
    await this.loadExperts(true);
  }
  
  /**
   * 下拉刷新
   */
  onRefresh() {
    this.refreshExperts();
  }
  
  /**
   * 加载更多
   */
  loadMore() {
    if (!this.noMore && !this.loading) {
      this.loadExperts();
    }
  }
  
  /**
   * 切换分类
   */
  switchCategory(categoryId: string) {
    if (this.currentCategory === categoryId) return;
    
    this.currentCategory = categoryId;
    this.page = 1;
    this.noMore = false;
    this.expertList = [];
    
    this.loadExperts(true);
  }
  
  /**
   * 格式化数量
   */
  formatCount(count: number): string {
    if (count < 1000) {
      return count.toString();
    } else if (count < 10000) {
      return (count / 1000).toFixed(1) + 'k';
    } else {
      return (count / 10000).toFixed(1) + 'w';
    }
  }
  
  /**
   * 查看专家详情
   */
  viewExpert(expert: Expert) {
    this.selectedExpert = expert;
    this.showExpertDetail = true;
  }
  
  /**
   * 获取专家等级文本
   */
  getLevelText(level: number): string {
    const levelMap: { [key: number]: string } = {
      1: '初级',
      2: '中级', 
      3: '高级',
      4: '专家',
      5: '权威'
    };
    return levelMap[level] || '初级';
  }
  
  /**
   * 添加到收藏
   */
  async addToFavorites(expert: Expert) {
    try {
      // 检查登录状态
      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录后再收藏专家',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            }
          }
        });
        return;
      }
      
      // 调用收藏API
      await post('/experts/favorite', {
        expertId: expert.id
      });
      
      uni.showToast({
        title: '收藏成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('收藏专家失败:', error);
      uni.showToast({
        title: '收藏失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 咨询专家
   */
  consultExpert(expert: Expert) {
    // 检查登录状态
    const token = uni.getStorageSync('token');
    const isGuest = uni.getStorageSync('isGuest');
    
    if (!token && !isGuest) {
      uni.showModal({
        title: '提示',
        content: '请先登录后再咨询专家',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    if (isGuest) {
      uni.showToast({
        title: '游客模式无法咨询专家',
        icon: 'none'
      });
      return;
    }
    
    // 显示咨询方式选择
    uni.showActionSheet({
      itemList: [
        `图文咨询 ¥${expert.textPrice}`,
        `语音咨询 ¥${expert.voicePrice}`,
        '查看详情'
      ],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.startConsultation(expert, 'text');
            break;
          case 1:
            this.startConsultation(expert, 'voice');
            break;
          case 2:
            this.viewExpert(expert);
            break;
        }
      }
    });
  }
  
  /**
   * 开始咨询
   */
  startConsultation(expert: Expert, type: 'text' | 'voice') {
    uni.navigateTo({
      url: `/pages/consult/consult?expertId=${expert.id}&type=${type}`
    });
  }
  
  /**
   * 跳转到搜索页面
   */
  goToSearch() {
    uni.navigateTo({
      url: '/pages/search/search?type=expert'
    });
  }
  
  /**
   * 获取模拟专家数据
   */
  getMockExperts(): Expert[] {
    return [
      {
        id: '1',
        name: '张医生',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor&image_size=square',
        title: '主任医师',
        hospital: '北京儿童医院',
        description: '从事儿科临床工作20年，擅长新生儿护理',
        fullDescription: '张医生拥有20年丰富的儿科临床经验，曾在多家三甲医院担任儿科主任。专业领域涵盖新生儿护理、婴儿喂养指导、疫苗接种咨询等。擅长处理各种新生儿常见问题，为数千个家庭提供了专业的育儿指导。',
        specialties: ['新生儿护理', '儿童发育', '疫苗接种'],
        experience: 15,
        rating: 4.9,
        consultCount: 2580,
        consultationCount: 2580,
        goodRatePercent: 98,
        responseTime: '5分钟内',
        textPrice: 50,
        voicePrice: 80,
        price: 199,
        isVerified: true,
        isOnline: true,
        level: 5,
        workTime: '周一至周五 9:00-18:00',
        category: 'pediatrics'
      },
      {
        id: '2',
        name: '李营养师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20nutritionist&image_size=square',
        title: '高级营养师',
        hospital: '上海妇幼保健院',
        description: '专业婴幼儿营养指导，科学喂养专家',
        fullDescription: '李营养师是国家注册营养师，专注于婴幼儿营养研究10余年。在辅食添加、营养搭配、过敏预防等方面有着丰富的实践经验，帮助众多家庭解决了宝宝的营养问题。',
        specialties: ['婴幼儿营养', '辅食添加', '营养搭配'],
        experience: 12,
        rating: 4.8,
        consultCount: 1890,
        consultationCount: 1890,
        goodRatePercent: 96,
        responseTime: '10分钟内',
        textPrice: 40,
        voicePrice: 60,
        price: 149,
        isVerified: true,
        isOnline: false,
        level: 4,
        workTime: '周一至周六 8:00-20:00',
        category: 'nutrition'
      },
      {
        id: '3',
        name: '王老师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20early%20education%20teacher&image_size=square',
        title: '早教专家',
        hospital: '广州早教中心',
        description: '专注婴幼儿心理发展和亲子关系指导',
        fullDescription: '王老师拥有儿童心理学硕士学位，从事儿童心理咨询工作8年。擅长婴幼儿睡眠训练、情绪管理、亲子互动指导，致力于帮助家长建立良好的亲子关系。',
        specialties: ['早期教育', '智力开发', '行为引导'],
        experience: 10,
        rating: 4.7,
        consultCount: 1456,
        consultationCount: 1456,
        goodRatePercent: 94,
        responseTime: '15分钟内',
        textPrice: 35,
        voicePrice: 55,
        price: 129,
        isVerified: true,
        isOnline: true,
        level: 3,
        workTime: '周二至周日 10:00-22:00',
        category: 'education'
      }
    ];
  }
}
</script>

<style lang="scss" scoped>
.expert-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

// 专家头像容器
.expert-avatar-container {
  position: relative;
  display: inline-block;
  
  .online-status {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background-color: #ccc;
    border: 2rpx solid #fff;
    
    &.online {
      background-color: #52c41a;
    }
  }
}

// 专家等级
.expert-level {
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  
  &.level-1 {
    background-color: #f0f0f0;
    color: #666;
  }
  
  &.level-2 {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  &.level-3 {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.level-4 {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.level-5 {
    background-color: #fff2e8;
    color: #fa541c;
  }
}

// 专家详情弹窗
.expert-detail-popup {
  padding: 40rpx;
  background-color: #fff;
  
  .detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    
    .expert-avatar-large {
      position: relative;
      margin-right: 30rpx;
      
      .avatar-img {
        width: 120rpx;
        height: 120rpx;
        border-radius: 60rpx;
      }
      
      .online-indicator {
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        background-color: #f5f5f5;
        
        &.online {
          background-color: #f6ffed;
          
          .status-text {
            color: #52c41a;
          }
        }
        
        .status-text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
    
    .expert-basic-info {
      flex: 1;
      
      .expert-name-large {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .expert-title-large {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 15rpx;
      }
      
      .expert-level-large {
        padding: 8rpx 16rpx;
        border-radius: 12rpx;
        font-size: 24rpx;
        display: inline-block;
      }
    }
  }
  
  .detail-content {
    .detail-section {
      margin-bottom: 40rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
      }
      
      .specialties-list {
        display: flex;
        flex-wrap: wrap;
        gap: 15rpx;
        
        .specialty-tag {
          padding: 10rpx 20rpx;
          background-color: #f0f8ff;
          color: #1890ff;
          border-radius: 20rpx;
          font-size: 24rpx;
        }
      }
      
      .expert-description {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
      }
      
      .stats-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 30rpx;
        
        .stat-item {
          text-align: center;
          padding: 30rpx;
          background-color: #f8f9fa;
          border-radius: 16rpx;
          
          .stat-number {
            display: block;
            font-size: 36rpx;
            font-weight: bold;
            color: #1890ff;
            margin-bottom: 10rpx;
          }
          
          .stat-label {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
      
      .work-time {
        font-size: 28rpx;
        color: #666;
        padding: 20rpx;
        background-color: #f8f9fa;
        border-radius: 12rpx;
      }
    }
  }
  
  .detail-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 40rpx;
    
    .action-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
      border: none;
      
      &.secondary {
        background-color: #f8f9fa;
        color: #666;
      }
      
      &.primary {
        background-color: #1890ff;
        color: #fff;
      }
    }
  }
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: white;
  
  .search-input {
    display: flex;
    align-items: center;
    height: 70rpx;
    padding: 0 25rpx;
    background-color: #f8f8f8;
    border-radius: 35rpx;
    
    .search-placeholder {
      margin-left: 15rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
}

.category-tabs {
  background-color: white;
  border-bottom: 1rpx solid #f0f0f0;
  
  .tabs-scroll {
    white-space: nowrap;
  }
  
  .tabs-list {
    display: flex;
    padding: 0 30rpx;
    
    .tab-item {
      flex-shrink: 0;
      padding: 25rpx 30rpx;
      margin-right: 10rpx;
      
      .tab-text {
        font-size: 28rpx;
        color: #666;
        transition: color 0.3s;
      }
      
      &.active {
        position: relative;
        
        .tab-text {
          color: #007aff;
          font-weight: 600;
        }
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #007aff;
          border-radius: 2rpx;
        }
      }
    }
  }
}

.expert-list {
  flex: 1;
  padding: 20rpx;
}

.expert-item {
  background-color: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  
  .expert-header {
    display: flex;
    margin-bottom: 20rpx;
    
    .expert-info {
      flex: 1;
      margin-left: 20rpx;
      
      .expert-name-row {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
        
        .expert-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-right: 10rpx;
        }
        
        .verified-badge {
          width: 24rpx;
          height: 24rpx;
          background-color: #007aff;
          border-radius: 12rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      
      .expert-title {
        display: block;
        font-size: 26rpx;
        color: #666;
        margin-bottom: 5rpx;
      }
      
      .expert-hospital {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .expert-actions {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      
      .rating-info {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
        
        .rating-text {
          margin-left: 5rpx;
          font-size: 26rpx;
          color: #333;
          font-weight: 600;
        }
      }
      
      .consult-count {
        font-size: 22rpx;
        color: #999;
      }
    }
  }
  
  .expert-specialties {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20rpx;
    
    .specialty-label {
      font-size: 26rpx;
      color: #666;
      margin-right: 10rpx;
      flex-shrink: 0;
    }
    
    .specialty-text {
      flex: 1;
      font-size: 26rpx;
      color: #333;
      line-height: 1.4;
    }
  }
  
  .expert-stats {
    display: flex;
    justify-content: space-around;
    padding: 20rpx 0;
    border-top: 1rpx solid #f0f0f0;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 20rpx;
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .stat-label {
        font-size: 22rpx;
        color: #999;
        margin-bottom: 8rpx;
      }
      
      .stat-value {
        font-size: 26rpx;
        font-weight: 600;
        color: #333;
      }
    }
  }
  
  .expert-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .price-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .price-label {
        font-size: 22rpx;
        color: #999;
        margin-bottom: 5rpx;
      }
      
      .price-value {
        font-size: 28rpx;
        font-weight: 600;
        color: #ff4757;
      }
    }
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  
  .loading-text {
    margin-left: 15rpx;
    font-size: 26rpx;
    color: #999;
  }
}

.no-more {
  text-align: center;
  padding: 40rpx;
  
  .no-more-text {
    font-size: 26rpx;
    color: #999;
  }
}
</style>